package com.hh.eduservice.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hh.eduservice.entity.EduSubject;
import com.hh.eduservice.entity.SubjectData;
import com.hh.eduservice.service.EduSubjectService;

import java.util.Map;

public class EduSubjectListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;
    public EduSubjectListener() {}
    public EduSubjectListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //数据
        EduSubject subject= oneSubjectExis(subjectData, eduSubjectService);
        if (subject == null) {
            EduSubject data = new EduSubject();
            data.setTitle(subjectData.getOneSubjectName().toUpperCase());
            data.setParentId("0");
            eduSubjectService.save(data);
            subject= oneSubjectExis(subjectData, eduSubjectService);
        }
        String pid = subject.getId();
        EduSubject subject2 = twoSubjectExis(subjectData, eduSubjectService, pid);
        if (subject2 == null) {
            EduSubject data = new EduSubject();
            data.setTitle(subjectData.getTwoSubjectName().toUpperCase());
            data.setParentId(pid);
            eduSubjectService.save(data);
        }
    }

    private EduSubject oneSubjectExis(SubjectData subjectData, EduSubjectService eduSubjectService) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title",subjectData.getOneSubjectName().toUpperCase());
        wrapper.eq("parent_id","0");
        return  eduSubjectService.getOne(wrapper);
    }

    private EduSubject twoSubjectExis(SubjectData subjectData, EduSubjectService eduSubjectService,String pid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title",subjectData.getTwoSubjectName().toUpperCase());
        wrapper.eq("parent_id",pid);
        return  eduSubjectService.getOne(wrapper);
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //表头
        System.out.println("表头:"+headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("结尾！");
    }
}
